/**
 * 游戏场景
 */
class MJGameSceneView extends V.GameView {
	//玩家面下牌
	public table_0: Table;
	public table_1: Table;
	public table_2: Table;
	public table_3: Table;
	//玩家手牌
	public hand_0: MyHand;
	public hand_1: OtherHand;
	public hand_2: OtherHand;
	public hand_3: OtherHand;
	//玩家打出的牌
	public showCard_0: ShowCard;
	public showCard_1: ShowCard;
	public showCard_2: ShowCard;
	public showCard_3: ShowCard;
	//玩家头像
	public player0: MJPlayerView;
	public player3: MJPlayerView;
	public player2: MJPlayerView;
	public player1: MJPlayerView;

	public gameName: eui.Label;//游戏信息
	public guizeLabel: eui.Label;//规则介绍
	public middle: Middle;//倒计时及方向
	public shaizi: ShaiZi;//骰子
	public settingButton: how.Button;//设置按钮
	public readyButton: how.Button;//准备按钮
	public actPanel: ActionPanel;//操作面板(吃碰杠听胡过)
	public banker:Number;

	/** 当前操作用户的位置 */
    public cSit:number;
    /** 当前操作用户 */
    public cPv:NewPlayerView;
	/** 胡牌消息 */
    public huPaiData:any;

	public constructor() {
		super();
		this.MAX_PLAYER = 4;
		this.skinName = "MJGameSceneSkin";
		this.Res = DataConfig.ResConfig[DataConfig.KIND_ID_MJ];
	}

	protected childrenCreated(): void {
		this.initPlayer();
		this.gameName.text = "红中麻将";
		this.guizeLabel.text = "游戏规则：红中麻将是常德麻将中的一种";
		this.readyButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.ready, this);//准备
		this.settingButton.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onSetting, this);
		how.SoundManager.stopMusic();
        //how.SoundManager.playMusic("dzpk_gamebg_mp3", false);
	}

	/**准备 */
	public ready(): void {
		console.log(">>> MJGameSceneView ready 准备");
		WebSocketInstance.getHallSocket().send(CMDConfig.SEND_READY);
	}

	/**设置 */
	public onSetting(): void {
		console.log(">>> MJGameSceneView onSetting 设置");
        how.module.ModuleManager.getInstance().initModule(SettingWindowModule, SettingWindowView, SettingWindowData);
	}

	/**调整时钟方向 */
	public onJoinGame(d: any): void {
		console.log(">>> MJGameSceneView onJoinGame 调整时钟方向");
		this.middle.setRotation(d.chair);
	}

	 /** 收到网络消息 */
    public onNetData(s:number, d:any):void{
        switch(s){
            case 100:{ //游戏开始
				this.huPaiData = null;
				D.App.table.waitReady = 999;//自动准备时长
                this.onGameStart(d);
                break;
            }case 103:{ //发送扑克-摸牌
				this.onUserInCard(d);
                break;
            }case 104:{ //出牌命令-打出牌
				this.onUserOutCard(d);
                break;
            }case 105:{ //操作提示
				this.onActionNotify(d);
                break;
            }case 106:{ //操作命令
				this.onUserAction(d);
                break;
            }case 107:{ //游戏结束
				this.onGameOver(d);
                break;
            }case 108:{ //胡牌
				this.onUserHuPai(d);
                break;
            }case 110:{ //用户托管
				//9,110 数据：{"bTrustee":0}
                break;
            }case 117:{ //听牌命令-提示
				//9,117 数据：{"cbOutCard":[18],"cbCardEye":[24],"cbFans":[1],"leftCount":[3]} 
                break;
            }case 119:{ //确认听牌
				this.player0.setTingUI();
                break;
            }case 120:{ //复盘消息
                break;
            }
        }
    }
	
	/**游戏开始 9,100
	 * {"lSiceCount":[6,6],"wBankerUser":1,"wCurrentUser":1,"wHeapHand":0,"wHeapTail":0,
	 "cbCardData":[1,1,1,3,8,8,35,36,37,38,40,41,41,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	 "cbHeapCardInfo":[[0,0],[0,0],[0,0],[0,0]],"cbLeftCardCount":59,"cbMagicCard":53,"cbUserAction":0,"cbFirstSendCard":2,
	 "cbBuHuaCard":[[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
	 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]],"cbBuHuaCount":[0,0,0,0]} 
	 * 
	*/
	public onGameStart(d: any): void {
		console.log(">>> MJGameSceneView onGameStart 游戏开始9,100");
		//隐藏准备按钮
		this.readyButton.visible = false;
		//掷筛子
		var lSiceCount = d.lSiceCount as Array<number>;
		this.shaizi.to(lSiceCount);
		//确定庄家和第一个操作的人
		this.banker = d.wBankerUser;
		this.cSit = d.wBankerUser;
		//显示中间的方向
		this.middle.visible = true;
		this.middle.showLight(this.c2p(d.wBankerUser));
		//设置自己手牌
		var cbCardData = d.cbCardData as Array<number>;
		cbCardData.length = d.wBankerUser == this.player0.chairId?14:13;
		this.hand_0.setData(cbCardData);
		this.hand_0.visible = true;
		//初始化其他玩家的手牌
		for (var i = 0; i < this.playerList.length; i++) {
			if (this.playerList[i].chairId != this.player0.chairId) {
				var hand = (this["hand_" + this.c2p(this.playerList[i].chairId)] as OtherHand);
				hand.visible = true;//显示别的玩家手牌
				if (d.wBankerUser == this.playerList[i].chairId) {
					hand.receiveHandCard();//初始化庄家手牌,多1张
				}
			}
		}
		//如果自己是庄家-显示操作
		if (d.wBankerUser == this.player0.chairId) {
			this.actPanel.checkAction(this.hand_0.handCards, 0, -1, this.hand_0.pengList);
		}
		for(let i=0;i<this.MAX_PLAYER;i++){
            this.playerList[i].onGameStart(d);
        }
		//手牌
		this.hand_0.onGameStart();
		//设置庄家标识
		(this["player" + this.c2p(d.wBankerUser)] as MJPlayerView).setwDUserUI();
		//this.hand_0.onTing(d);
	}

	/**用户出牌 9,1*/
	public userOutCard(value: number): void {
		console.log(">>> MJGameSceneView userOutCard 发送出牌");
		if (this.player0.chairId == this.cSit) {
			WebSocketInstance.getHallSocket().send(CMDConfig.SEND_OUT_CARD, { cbCardData: value, bTing: this.player0.isTing || ActionPanel.readyTing?1:0 });
			ActionPanel.readyTing = false;
			this.cSit = -1;
		}
	}
	
	/**
	 * 收到用户摸牌 
	 * 9,103 数据：{"wCurrentUser":0,"bTail":0,"cbActionMask":80,"cbCardData":33} 
	 * */
	public onUserInCard(d: any): void {
		console.log(">>> MJGameSceneView onUserInCard 收到用户摸牌");
		this.middle.showLight(this.c2p(d.wCurrentUser));
		this.cSit = d.wCurrentUser;
		if (d.wCurrentUser == this.player0.chairId) {
			this.hand_0.receiveHandCard(d.cbCardData);
			this.actPanel.checkAction(this.hand_0.handCards, 0, -1, this.hand_0.pengList);
			if (this.player0.isTing) {
				//玩家已经听牌
				//Robort.getInstance().run(this.hand_0);
			}
		} else {
			(this["hand_" + this.c2p(d.wCurrentUser)] as OtherHand).receiveHandCard();
		}
	}

	/**收到用户出牌 
	 * 9,104 数据：{"wOutCardUser":2,"cbOutCardData":3}
	 */
	public onUserOutCard(d: any): void {
		console.log(">>> MJGameSceneView onUserOutCard 收到用户出牌");
		var sex = (<MJPlayerView>this.playerList[this.c2p(d.wOutCardUser)]).sex == 0 ? "w" : "m";
		how.SoundManager.playEffect(sex + "-" + d.cbOutCardData + "_mp3");
		this.middle.stopEffect();
		this.actPanel.visible = false;
		if (d.wOutCardUser == this.player0.chairId) {//如果是自己
			this.hand_0.onUserOutCard(d);
			this.hand_0.loseCard(d.cbOutCardData);
			this.hand_0.hideReceiveCard();
		} else {
			(this["hand_" + this.c2p(d.wOutCardUser)] as OtherHand).hideReceiveCard();
			//this.actPanel.checkAction(this.hand_0.handCards, d.cbOutCardData, d.wOutCardUser, this.hand_0.pengList);
		}
		//设置当前出牌用户面下牌桌数据，其他人隐藏标记
		(this["table_" + this.c2p(d.wOutCardUser)] as Table).setCard(d.cbOutCardData);
		(this["table_" + (this.c2p(d.wOutCardUser) + 1 > 3 ? 0 : this.c2p(d.wOutCardUser) + 1)] as Table).hideLight();
		(this["showCard_" + this.c2p(d.wOutCardUser)] as ShowCard).setData(d.cbOutCardData);
	}

	/**
	 * 收到操作提示-替换checkAction
	 * 9,105 数据：{"wResumeUser":1,"cbActionCard":3,"cbActionMask":8} 
	 */
	public onActionNotify(d: any): void {
		console.log(">>> MJGameSceneView onActionNotify 收到操作提示 ");
		this.cSit = d.cbActionCard;
		this.actPanel.operateCard = d.cbActionCard;
		this.actPanel.checkAction(this.hand_0.handCards, d.cbActionCard, d.wResumeUser, this.hand_0.pengList);
	}

	/**收到玩家操作 (当前操作玩家、扑克、操作代码、供应玩家)
	 * 9,106 数据：{"wOperateUser":1,"cbOperateCard":34,"cbOperateCode":16,"wProvideUser":2}
	*/
	public onUserAction(d: any): void {
		console.log(">>> MJGameSceneView onUserAction 收到玩家操作 ");
		this.middle.stopEffect();
		this.cSit = d.wOperateUser;
		this.actPanel.operateCard = d.cbOperateCard;
		this.actPanel.visible = false;
		//处理操作，如果是胡牌则不处理-单游戏结束
		if (d.cbOperateCode != MjLogic.Prio.ChiHu || d.cbOperateCode != MjLogic.Prio.ZiMo) {
			this.middle.showLight(this.c2p(d.wOperateUser));
			if (d.wOperateUser == this.player0.chairId) {//如果是自己操作
				this.hand_0.pengGang(d);//吃碰杠处理
				if (d.cbOperateCode != MjLogic.Prio.Ting) {
					var canHu = true;
					if (d.cbOperateCode == MjLogic.Prio.ChiLeft || d.cbOperateCode == MjLogic.Prio.ChiRight 
					|| d.cbOperateCode == MjLogic.Prio.ChiMiddle || d.cbOperateCode == MjLogic.Prio.Peng ) {
						canHu = false;
					}
					this.actPanel.checkAction(this.hand_0.handCards, 0, -1, this.hand_0.pengList, canHu);
				}
			} else {
				(this["hand_" + this.c2p(d.wOperateUser)] as OtherHand).pengGang(d);//吃碰杠处理
			}
			if ((d.wProvideUser || d.wProvideUser == 0) && d.cbOperateCode != MjLogic.Prio.Gang) {
				(this["table_" + this.c2p(d.wProvideUser)] as Table).loseCard();
			}
		}
		var sex = (<MJPlayerView>this.playerList[this.c2p(d.wOperateUser)]).sex == 0 ? "w" : "m";
		switch (d.cbOperateCode) {
			case MjLogic.Prio.Peng:
				how.SoundManager.playEffect(sex + "-peng_mp3");
				break;
			case MjLogic.Prio.ChiLeft:
			case MjLogic.Prio.ChiMiddle:
			case MjLogic.Prio.ChiRight:
				how.SoundManager.playEffect(sex + "-chi_mp3");
				break;
			//how.SoundManager.playEffect(sex + "-ag_mp3");
			case MjLogic.Prio.Gang:
				how.SoundManager.playEffect(sex + "-gang_mp3");
				break;
		}
	}

	/**收到某玩家胡牌信息 胡牌玩家、点炮玩家、赢分、胡的牌
	 * 9,108 数据：{"wChiHuUser":0,"wProviderUser":0,"lGameScore":300,"cbChiHuCard":33}
	 */
	public onUserHuPai(d: any): void {
		console.log(">>> MJGameSceneView onUserHuPai 收到某玩家胡牌信息 ");
		this.huPaiData = d;
		var sex = (<MJPlayerView>this.playerList[this.c2p(d.wChiHuUser)]).sex == 0 ? "w" : "m";
		how.SoundManager.playEffect(sex + "-hu_mp3");
	}

	/**单局游戏结束 
	 * //9,107 数据：{"cbCardCount":[14,10,13,13],"cbCardData":[[5,7,20,22,33,34,39,39,39,39,53,53,53,53],[2,5,7,7,8,9,17,18,20,22,0,0,0,0],[1,1,1,3,8,8,35,36,37,38,40,41,41,0],[9,9,19,19,19,19,33,34,35,36,37,38,40,0]],"wProvideUser":[0,65535,65535,65535],"dwChiHuRight":[16384,0,0,0],"lGameScore":[18,-6,-6,-6],"lGameTax":[0,0,0,0],"wWinOrder":[0,0,0,0],"wGangScore":[0,0,0,0],"wLostFanShu":[[0,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]],"wLeftUser":65535,"bPiao":[0,0,0,0],"bLiuju":0,"cbMagicCard":0,"cbZhuaMaCardData":[41,40,38,37,0,0,0,0,0,0],"cbIsZhuaZhong":[1,0,0,1,0,0,0,0,0,0],"cbAGNum":[0,0,0,0],"cbPGNum":[0,0,0,0],"cbJGNum":[0,0,0,0],"cbFGNum":[0,0,0,0],"cbLeftCards":[1,2,4,5,6,7,8,9,2,4,5,6,20,21,22,23,24,25,17,18,20,21,22,23,24,25,17,18,4,21,6,23,24,25,17,18,4,21,6,23,24,25,33,34,35,36,37,38,40,41,33,34,35,36,0,0,0,0,0]} 
	*/
	public onGameOver(d: any): void {
		console.log(">>> MJGameSceneView onGameOver 单局游戏结束");
		var window = how.Application.openWindow(SettleWindow) as SettleWindow;
		window.setData(d);
		//if (this.roomData.nowGames == this.roomData.totalGames) {
		//	window.theGameEnd();
		//}

		for (let i = 0; i < 4; i++) {
			(this["player" + this.c2p(i)] as MJPlayerView).onGameEnd(d.lGameScore[i]);
			(this["hand_" + i] as MyHand).clear();
			(this["table_" + i] as Table).clear();
		}
		this.middle.clear();
	}

	/**断线重连 */
	public onReconnect(d: any): void {
		/*this.ui.onReconnect(d);
		this.cSit = d.current;
		this.middle.setRotation(this.player0.chairId);
		this.middle.showLight(d.current == -1 ? d.lastPutChair : d.current);
		for (var j = 0; j < 4; j++) {
			for (var i = 0; i < d.putCardList[j].length; i++) {
				if (d.putCardList[j] && d.putCardList[j][i]) {
					(this["table_" + how.ToolBox.getSeatID(j, this.player0.chairId)] as Table).setCard(d.putCardList[j][i]);
					if (d.lastPutChair != j || i != d.putCardList[j].length - 1 || d.putCardList[j][i] != d.lastPutCard) {
						(this["table_" 
						+ how.ToolBox.getSeatID(j, this.player0.chairId)] as Table).hideLight();
					}
				}
			}
		}
		for (var n = 0; n < 4; n++) {
			(this["hand_" + n] as MyHand).visible = true;
			if (d.operateList[n] && d.operateList[n].length > 0) {
				for (let m = 0; m < d.operateList[n].length; m++) {
					(this["hand_" + how.ToolBox.getSeatID(n, this.player0.chairId)] as MyHand).peng(d.operateList[n][m], true);
				}
			}
		}
		if (d.lastTouchChair == this.player0.chairId) {
			var index = d.cards.indexOf(d.lastTouchCard);
			d.cards.splice(index, 1);
			this.hand_0.setData(d.cards);
			this.hand_0.receiveHandCard(d.lastTouchCard);
		} else {
			this.hand_0.setData(d.cards);
		}
		this.hand_0.visible = true;
		for (var k = 0; k < d.cardCounts.length; k++) {
			if (k != this.player0.chairId) {
				if (k == d.current) {
					d.cardCounts[k]--;
					(this["hand_" + how.ToolBox.getSeatID(k, this.player0.chairId)] as OtherHand).receiveHandCard();
				}
				(this["hand_" + how.ToolBox.getSeatID(k, this.player0.chairId)] as OtherHand).setCardByNumber(d.cardCounts[k]);
			}
		}
		for (let z = 0; z < d.userList.length; z++) {
			if (z == this.player0.chairId) {
				this.userData.isTing = d.userList[z].isTing;
				if (this.userData.isTing) {
					G.event.dispatch(ActionPanel.ONTING, MjLogic.checkTing(this.hand_0.handCards, this.hand_0.pengList));
					this.hand_0.receiveCard.card.hight = true;
					Robort.getInstance().run(this.hand_0);
				}
			} else {
				this.roomData.playerList[z].isTing = d.userList[z].isTing;
			}
		}
		if (d.actionData[this.player0.chairId] && d.actionData[this.player0.chairId].length > 0) {
			this.actPanel.checkAction(this.hand_0.handCards, d.lastPutCard, d.lastPutChair, this.hand_0.pengList);
		} else if (this.player0.chairId == d.current) {
			this.actPanel.checkAction(this.hand_0.handCards, 0, -1, this.hand_0.pengList);
		}*/
	}
}